package com.demo.jfinal.job;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import com.core.sgip.client.SGIP2DownClient;
import com.demo.jfinal.model.ApiDownstream;
import com.demo.jfinal.model.SmsAccept;
import com.jfinal.plugin.activerecord.Db;

/**
 * 向客户推送上行数据
 * 
 * @author Guoxing
 *
 */
public class Request2DownMOJob implements Job {
	private static Logger log = Logger.getLogger(Request2DownMOJob.class);

	/*
	 * 从表里拿数据向下游推送状态
	 */
	@Override
	public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {

		log.info("向下游推送上行信息任务正在执行：" + System.currentTimeMillis());
		Date date = new Date();
		// 获取当前数据

		List<SmsAccept> smsAcceptList = SmsAccept.dao
				.find("SELECT T.* FROM SMS_ACCEPT T WHERE T.IS_DISPOSE = 'N' AND T.DATE_TYPE='1' and T.INSERT_DATE <= ?", date);
		if (smsAcceptList == null || smsAcceptList.isEmpty()) {
			log.info("Request2DownMOJob无数据处理");
			return;
		} else {
			Db.batch("update sms_accept set IS_DISPOSE = 'Y' where 1=1 and ID = ? ", "ID", smsAcceptList,
					smsAcceptList.size());
		}
		List<String> list = new ArrayList<String>();
		// 根据客户的配置信息 拿到 客户提供的sgip服务，去推送
		SmsAccept smsOrders = new SmsAccept();
		for (int i = 0; i < smsAcceptList.size(); i++) {
			smsOrders = smsAcceptList.get(i);
			String phoneNo = smsOrders.getStr("PHONE_NO");
			String recontent = smsOrders.getStr("RE_CONTENT");

			log.info("正在处理数据：phoneno = " + phoneNo + ",orderId = " + smsOrders.getStr("ORDER_ID"));

			list.add(phoneNo);
			// 拿到客户信息 ，去回调状态给对应的客户
			int confId = smsOrders.getInt("CONF_ID");

			ApiDownstream apiDownstream = new ApiDownstream();
			apiDownstream = ApiDownstream.dao.getApiDownstreamCacheById(String.valueOf(confId));
			if (apiDownstream == null) {
				ApiDownstream.dao.findFirst(
						"select * from sms_api_downstream_config c where 1=1 and PROTOCOL_TYPE = '1' and CONF_ID = ?",
						confId);
			}
			if (apiDownstream == null) {
				log.info("向下游推送上行信息时未获取到ID=" + confId + "的客户配置信息");
				continue;
			}
			// 客户ip：port
			String ipportkeypas = apiDownstream.getStr("UP_STREAM_POST");

			log.info("向下游推送上行信息参数conf_id = " + confId + ",ipportkeypas = " + ipportkeypas);
			// String appkey = apiDownstream.getStr("APPKEY");
			// String password = apiDownstream.getStr("SECURTY");
			String ip = ipportkeypas.split(":")[0];
			String port = ipportkeypas.split(":")[1];
			String appkey = ipportkeypas.split(":")[2];
			String password = ipportkeypas.split(":")[3];

			try {
				SGIP2DownClient.sendMsgMO(ip, port, appkey, password, list, recontent);
			} catch (Exception e) {
				e.printStackTrace();
			}

		}

	}

}
